package com.shop.loan.rentaldata;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.vo.RentalPayVo;
import com.shop.loan.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付模块
 */
@Slf4j
@Component
public class RentalPayUtil {

    @Value("${api.rental_pay.apiKey}")
    private String apiKey;

    @Value("${api.rental_pay.apiSecret}")
    private String apiSecret;

    @Value("${api.rental_pay.url}")
    private String url;


    private static String nonce = "smazxxrssmzdpxys";

    /**
     * 查询余额
     *
     * @return
     */
    public JSONObject getBalance() {
        JSONObject balanceJs = new JSONObject();
        BigDecimal assetBalance = BigDecimal.ZERO, loanBalance = BigDecimal.ZERO, rdBalance = BigDecimal.ZERO;
        String apiUrl = url + "/api/user/balance";
        JSONObject jsonObject = new JSONObject();
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【getBalance】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            JSONArray jsonArray = JSON.parseArray(resultJs.getString("data"));
            for (Object item : jsonArray) {
                JSONObject itemJs = JSON.parseObject(JSON.toJSONString(item));

//                if (itemJs.getInteger("type") == CompanyType.loan.getType().intValue()) {
//                     loanBalance = itemJs.getBigDecimal("balance");
//                } else if (itemJs.getInteger("type") == CompanyType.asset.getType().intValue()) {
//                    assetBalance = itemJs.getBigDecimal("balance");
//                } else if (itemJs.getInteger("type") == CompanyType.rd.getType().intValue()) {
//                    rdBalance = itemJs.getBigDecimal("balance");
//                }
            }
        }
        balanceJs.put("assetBalance", assetBalance);
        balanceJs.put("loanBalance", loanBalance);
        balanceJs.put("rdBalance", rdBalance);
        return balanceJs;
    }

    /**
     * 查询余额记录
     *
     * @return
     */
    public JSONObject getBalanceLog(Integer pageNum, Integer pageSize, Integer type, Integer useType) {
        String apiUrl = url + "/api/user/getBalanceLog";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum", pageNum);
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("type", type);
        jsonObject.put("useType", useType);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【getBalanceLog】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }

    /**
     * 提交提现申请
     *
     * @return
     */
    public ResResult withdrawApply(BigDecimal number,Integer type) {
        String apiUrl = url + "/api/user/withdraw/apply";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("number", number);
        jsonObject.put("type", type);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【withdrawApply】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS);
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }

    /**
     * 获取绑卡验证码
     *
     * @param payVo
     * @return
     */
    public ResResult signing(RentalPayVo payVo) {
        String apiUrl = url + "/api/pay/signing";
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(JSON.toJSONString(payVo))
                .execute().body();
        log.info("非凡支付【signing】 参数:{},返回:{}", JSON.toJSONString(payVo), result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS, resultJs.getString("data"));
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }

    /**
     * 提交绑卡验证码
     *
     * @param payVo
     * @return
     */
    public ResResult signMessage(RentalPayVo payVo) {
        String apiUrl = url + "/api/pay/signMessage";
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(JSON.toJSONString(payVo))
                .execute().body();
        log.info("非凡支付【signMessage】 参数:{},返回:{}", JSON.toJSONString(payVo), result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS, resultJs.getString("data"));
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }


    /**
     * 解绑银行卡
     *
     * @param userId
     * @param bindCardId
     * @return
     */
    public ResResult unSign(String userId, String bindCardId) {
        String apiUrl = url + "/api/pay/unSign";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userId);
        jsonObject.put("orderNo", Util.getOutTradeNo());
        jsonObject.put("bindCardId", bindCardId);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【unSign】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS);
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }

    /**
     * 放款
     *
     * @param payVo
     * @return
     */
    public ResResult loan(RentalPayVo payVo) {
        String apiUrl = url + "/api/pay/loan";
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(JSON.toJSONString(payVo))
                .execute().body();
        log.info("非凡支付【loan】 参数:{},返回:{}", JSON.toJSONString(payVo), result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS, resultJs.getString("data"));
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }

    /**
     * 还款
     *
     * @param payVo
     * @return
     */
    public ResResult pay(RentalPayVo payVo) {
        String apiUrl = url + "/api/pay/pay";
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(JSON.toJSONString(payVo))
                .execute().body();
        log.info("非凡支付【pay】 参数:{},返回:{}", JSON.toJSONString(payVo), result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs == null) {
            return new ResResult(Code.FAIL);
        }
        if (resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return new ResResult(Code.SUCCESS, resultJs.getString("data"));
        }
        return new ResResult(Code.FAIL.getCode(), resultJs.getString("msg"), null);
    }


    /**
     * 查看提现申请记录
     *
     * @return
     */
    public JSONObject getWithdrawLog(Integer pageNum, Integer pageSize) {
        String apiUrl = url + "/api/user/withdraw/log";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum", pageNum);
        jsonObject.put("pageSize", pageSize);
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【withdrawLog】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    /**
     * 查询小贷和资管信息
     *
     * @return
     */
    public JSONObject getCompany() {
        String apiUrl = url + "/api/user/getCompany";
        JSONObject jsonObject = new JSONObject();
        String result = HttpRequest.post(apiUrl)
                .addHeaders(getHeadMap())
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("非凡支付【getCompany】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("code") && resultJs.getInteger("code") == 1) {
            return resultJs.getJSONObject("data");
        }
        return null;
    }


    private Map getHeadMap() {
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(apiSecret, nonce, curTime);
        Map headMap = new HashMap();
        headMap.put("ApiKey", apiKey);
        headMap.put("Nonce", nonce);
        headMap.put("CurTime", curTime);
        headMap.put("CheckSum", checkSum);
        return headMap;
    }


}
